package com.zf.nacos.discovery;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.registry.NacosRegistration;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * nacos服务发现相关
 */
@RestController
@RequestMapping("/dis")
public class NacosDiscoveryTestController {
    /**
     * 服务管理：查询、注册、下线服务
     */
    @Resource
    private NacosServiceManager serviceManager;
    /**
     * application和bootstrap中配置的 nacos服务注册与发现中心配置信息，会自动生成一些信息（如服务名、IP、端口、元信息等）
     */
    @Resource
    private NacosDiscoveryProperties nacosDiscoveryProperties;
    /**
     * NacosRegistration 服务注册到 Nacos 时使用的信息，包含 NacosDiscoveryProperties 中生成的信息，同时多了一些元信息和其他内容
     */
    @Resource
    private NacosRegistration nacosRegistration;

    @GetMapping("/serviceInfo")
    public List<Instance> getServiceInfo(@RequestParam(name = "serviceId") String serviceId) throws NacosException {
        // 获取指定服务的所有在线实例， 不传分组则是默认组
        List<Instance> instanceList = serviceManager.getNamingService().getAllInstances(serviceId);
        // List<Instance> instanceList = serviceManager.getNamingService().getAllInstances(serviceId, nacosDiscoveryProperties.getGroup());
        return instanceList;
    }


    /**
     * 获取当前服务的所有实例
     */
    @GetMapping("/currentServiceInfo")
    public List<Instance> currentServiceInfo() throws NacosException {
        NamingService namingService = serviceManager.getNamingService();
        // 获取该服务的所有在线实例，分组是默认组
        List<Instance> allInstances = Optional.ofNullable(namingService.getAllInstances(nacosDiscoveryProperties.getService())).orElse(Collections.emptyList());
        // List<Instance> allInstances = Optional.ofNullable(namingService.getAllInstances(nacosDiscoveryProperties.getService(), nacosDiscoveryProperties.getGroup())).orElse(Collections.emptyList());
        // for (Instance instance : allInstances) {
        //     // 是否下线
        //     boolean enabled = instance.isEnabled();
        // }

        // 可以使用该接口获取指定服务的所有实例，包括被下线的：http://localhost:8848/nacos/v1/ns/catalog/instances?&serviceName=nacos-sample&clusterName=DEFAULT&groupName=DEFAULT_GROUP&pageSize=10&pageNo=1&namespaceId=
        // 该接口返回
        // {
        //      private List<Instance> list;
        //      private int count;
        // }

        return allInstances;
    }


    /**
     * 注册服务，如果服务已经注册（无论是否先下线或者不健康）则不做任何操作。
     * 判断注册的规则是 “serviceId+group+ip+port”
     */
    @GetMapping("/registerCurService")
    public String registerCurService() throws NacosException {
        String ip = nacosDiscoveryProperties.getIp();
        int port = nacosDiscoveryProperties.getPort();
        String serviceId = nacosDiscoveryProperties.getService();
        String group = nacosDiscoveryProperties.getGroup();
        Map<String, String> metadata = nacosDiscoveryProperties.getMetadata();
        Instance instance = new Instance();
        instance.setIp(ip);
        instance.setPort(port);
        instance.setMetadata(metadata);
        // 注册实例
        // serviceManager.getNamingService().registerInstance(serviceId, group, ip, port);
        serviceManager.getNamingService().registerInstance(serviceId, group, instance);

        return "success";
    }

    /**
     * 删除服务，如果已被删除则不做任何操作
     * 判断规则是 “serviceId+group+ip+port”
     */
    @GetMapping("/deregisterCurService")
    public String deregisterCurService() throws NacosException {
        String ip = nacosDiscoveryProperties.getIp();
        int port = nacosDiscoveryProperties.getPort();
        String serviceId = nacosDiscoveryProperties.getService();
        String group = nacosDiscoveryProperties.getGroup();
        // 删除实例
        serviceManager.getNamingService().deregisterInstance(serviceId, group, ip, port);
        return "success";
    }

}
